package cn.innosmart.aq.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.tutk.p2p.ConnectionEntity;
import com.tutk.p2p.ConnectionManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.SceneListAdapter;
import cn.innosmart.aq.bean.ActionBean;
import cn.innosmart.aq.bean.AquariumBean;
import cn.innosmart.aq.bean.CommandBean;
import cn.innosmart.aq.bean.DeviceBean;
import cn.innosmart.aq.bean.RuleBean;
import cn.innosmart.aq.bean.SceneBean;
import cn.innosmart.aq.bean.ScheduleBean;
import cn.innosmart.aq.customize.CustomsizeDialog;
import cn.innosmart.aq.manager.RuleManager;
import cn.innosmart.aq.manager.SceneManager;
import cn.innosmart.aq.manager.ScheduleManager;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.view.activity.SceneActivity;

/**
 * Created by David on 2015/11/24.
 */
public class BoxDetailSceneFragment extends BaseFragment {
    private final int LOADINGOVER = 0;
    private final int DATACHANGE = 7;
    int[] priorityStrIds = new int[]{R.string.priority_ignore_simple, R.string.priority_normal_simple, R.string.priority_important_simple, R.string.priority_high_important_simple};
    private View view;
    private ListView listView;
    private SceneListAdapter sceneListAdapter;
    private ConnectionEntity connectionEntity;
    private BoxDetailAutoFragment parent;
    private AquariumBean aquariumBean;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOADINGOVER:
                    hideLoadingDialog();
                    break;
                case DATACHANGE:
                    onResume();
                    parent.refresh();
                    break;
            }
        }
    };
    private View.OnClickListener onModifyClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_modify:
                    modifyScene(v);
                    break;
                case R.id.tv_control:
                    excuteScene(v);
                    break;
                case R.id.tv_delete:
                    SceneBean sceneBean = (SceneBean) v.getTag();
                    showSureDeleteDialog(sceneBean.getTitle(), sceneBean);
                    break;
                case R.id.tv_info:
                    showSceneInfo(v);
                    break;
            }
        }
    };

    private void modifyScene(View v) {
        SceneBean sceneBean = (SceneBean) v.getTag();
        Intent intentScene = new Intent(getActivity(), SceneActivity.class);
        intentScene.putExtra("scene", sceneBean.getId());
        startActivity(intentScene);
        getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_auto_example, container, false);
        connectionEntity = ConnectionManager.getInstance().getCurrentConnectionEntity();
        parent = (BoxDetailAutoFragment) getParentFragment();
        aquariumBean = parent.getAquariumBean();
        listView = (ListView) view.findViewById(R.id.lv_auto);
        TextView emptyView = (TextView) view.findViewById(R.id.empty_view);
        emptyView.setText(R.string.no_scene_data);
        listView.setEmptyView(emptyView);
        sceneListAdapter = new SceneListAdapter(getActivity(), aquariumBean);
        sceneListAdapter.setOnModifyClickListener(onModifyClickListener);
        listView.setAdapter(sceneListAdapter);
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        refresh();
        startModify(parent.isModify);
    }

    @Override
    protected void refresh() {
        if (sceneListAdapter != null){
            aquariumBean = parent.getAquariumBean();
            sceneListAdapter.setAquariumBean(aquariumBean);
            sceneListAdapter.refresh();
        }
    }

    @Override
    protected void startModify(boolean startModify) {
        if (sceneListAdapter != null)
            sceneListAdapter.startModify(startModify);
    }

    private void excuteScene(View v) {
        showLoadingDialog(getActivity());
        SceneBean sceneBean = (SceneBean) v.getTag();
        JSONObject jsonParams = new JSONObject();
        try {
            jsonParams.put("id", sceneBean.getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        SceneManager.getInstance().Execute(connectionEntity, jsonParams.toString(), new SceneManager.ExecuteCallBack() {
            @Override
            public void onExecuteResponseCallBack(int ret) {
                if (ret == 0) {
                    showToast(getActivity().getString(R.string.scene_enable));
                    hideLoadingDialog();
                } else {
                    showToast(getActivity().getString(R.string.scene_enable_failed));
                    hideLoadingDialog();
                }
            }
        });
    }

    private void showSureDeleteDialog(String name, final Object object) {
        final CustomsizeDialog customsizeDialog = new CustomsizeDialog(getActivity());
        customsizeDialog.setTitle(getActivity().getString(R.string.dialog_title_alert));
        customsizeDialog.setContent(String.format(getString(R.string.dialog_content_delete_sure),name));
        customsizeDialog.setNegativeButton(getActivity().getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                customsizeDialog.dismiss();
            }
        });
        customsizeDialog.setPositiveButton(getActivity().getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoadingDialog(getActivity());
                final SceneBean sceneBeanDelete = (SceneBean) object;
                SceneManager.getInstance().Remove(connectionEntity, sceneBeanDelete.toDeleteParams(), new SceneManager.RemoveCallBack() {
                    @Override
                    public void onRemoveResponseCallBack(int ret, String ruleid) {
                        if (ret == 0) {
                            analysizeSchedules(sceneBeanDelete.getId());
                            analysizeRules(sceneBeanDelete.getId());
                            aquariumBean.getSceneList().remove(sceneBeanDelete);
                            mHandler.sendEmptyMessage(DATACHANGE);
                            hideLoadingDialog();
                        }
                    }
                });
                customsizeDialog.dismiss();
            }
        });
        customsizeDialog.show();
    }

    /**
     * 删除场景后要去判断规则中是否含有场景
     * 如果有则需要将执行部分中相关场景移除并更新UI
     * @param sceneId
     */
    private void analysizeRules(String sceneId) {
        for (int i = 0; i < aquariumBean.getRuleList().size(); i++) {
            final RuleBean ruleBean = aquariumBean.getRuleList().get(i);
            ArrayList<CommandBean> commandBeans = ruleBean.getCommands();
            for (int j = 0; j < commandBeans.size(); j++) {
                CommandBean commandBean = commandBeans.get(j);
                String type = commandBean.getType();
                if (type.equals("scene")) {
                    if (sceneId.equals(commandBean.getScene_id())) {
                        commandBeans.remove(j);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                RuleManager.getInstance().Update(connectionEntity, ruleBean.toParams().toString(), new RuleManager.UpdateCallBack() {
                                    @Override
                                    public void onUpdateResponseCallBack(int ret, String ruleid) {
                                        if (ret != 0) {
                                            SystemConstant.ruleList = null;
                                        }
                                    }
                                });
                            }
                        }).start();
                    }
                }
            }
        }
    }

    /**
     * 删除场景后要去判断定时中是否含有场景
     * 如果有则需要将执行部分中相关场景移除并更新UI
     *
     * @param sceneId
     */
    private void analysizeSchedules(String sceneId) {
        for (int i = 0; i < aquariumBean.getScheduleList().size(); i++) {
            final ScheduleBean scheduleBean = aquariumBean.getScheduleList().get(i);
            ArrayList<CommandBean> commandBeans = scheduleBean.getScheduleCommands();
            CommandBean commandBean=commandBeans.get(0);
            if(commandBean.getType().equals("scene")){
                if(commandBean.getScene_id().equals(sceneId)){
                    aquariumBean.getScheduleList().remove(scheduleBean);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            ScheduleManager.getInstance().Remove(connectionEntity, scheduleBean.toDeleteParams(), new ScheduleManager.RemoveCallBack() {
                                @Override
                                public void onRemoveResponseCallBack(int ret, String ruleid) {
                                    if (ret != 0) {
                                        SystemConstant.scheduleList = null;
                                    }
                                }
                            });
                        }
                    }).start();
                    i--;
                }
            }
        }
    }

    private void showSceneInfo(View v) {
        final CustomsizeDialog autoInfoDialog = new CustomsizeDialog(getActivity());
        autoInfoDialog.setTitle(getString(R.string.auto_info_title));
        SceneBean sceneBean = (SceneBean) v.getTag();
        spellSceneInfo(sceneBean, autoInfoDialog);
        autoInfoDialog.setPositiveButton(R.string.sure, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                autoInfoDialog.dismiss();
            }
        });
        autoInfoDialog.show();
    }
    private void spellSceneInfo(SceneBean sceneBean, CustomsizeDialog autoInfoDialog) {
        StringBuilder autoInfo = new StringBuilder();
        ArrayList<ActionBean> arrayList = sceneBean.getCommands();
        for (int j = 1; j < arrayList.size() + 1; j++) {
            ActionBean actionBean = arrayList.get(j - 1);
            String command = "";
            if ("sleep".equals(actionBean.getField())) {
                command = getString(R.string.sleep) + actionBean.getValue()+" " + getString(R.string.sleep_unit);
            } else if ("sensorvalue".equals(actionBean.getField())) {
                DeviceBean deviceBean = SystemConstant.deviceBeanHashMap.get(actionBean.getAddress());
                double value = actionBean.getValue();
                if (value == 255) {
                    command = deviceBean.getName() +" "+getString(R.string.open);
                } else if (value == 0) {
                    command = deviceBean.getName() +" "+ getString(R.string.close);
                }
            }
            if (j == 1) {
                autoInfo.append(j + "、" + command);
            } else {
                autoInfo.append("\r\n");
                autoInfo.append(j + "、" + command);
            }
        }
        autoInfoDialog.setCommandContent(getString(R.string.command), autoInfo.toString());
        if (TextUtils.isEmpty(sceneBean.getPns())) {
            autoInfoDialog.setPushContent(getActivity().getString(R.string.push_status),getActivity().getString(R.string.close));
        } else {
            autoInfoDialog.setPushContent(getActivity().getString(R.string.push_status), getActivity().getString(R.string.open));
        }
        if (sceneBean.pns_priority != 0)
            autoInfoDialog.setImportanceContent(getActivity().getString(R.string.alarm_priority_title), getActivity().getString(priorityStrIds[sceneBean.pns_priority]));
        autoInfo = null;
    }
}
